<template>
    <!-- 表单 -->
    <el-form :model="form" label-width="120px">
        <el-form-item label="学号">
            <el-input v-model="formData.id" />
        </el-form-item>
        <el-form-item label="姓名">
            <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="年龄">
            <el-input v-model="formData.age" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="clearHandle">清空输入框</el-button>
            <el-button type="primary" @click="submitHandle">提交</el-button>
        </el-form-item>
    </el-form>

    <!-- 学生总数： -->
    <el-text>学生总数：{{ total }}</el-text>

    <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="学号" width="180" />
        <el-table-column prop="name" label="姓名" width="180" />
        <el-table-column prop="age" label="年龄" width="180" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button size="small" @click="editHandle(scope.$index)">修改</el-button>
                <el-button size="small" type="danger" @click="deleteHandle(scope.$index)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
const formData = ref({
    id: '',
    name: '',
    age: ''
})
const tableData = ref([])
// 一个计算属性 ref
const total = computed(() => {
    return tableData.value.length
})

const status = ref("add")

// 提交
const submitHandle = () => {
    if (status.value == "add") {
        tableData.value.push(formData.value)
    }
    clearHandle()
}

// 清空输入框
const clearHandle = () => {
    formData.value = {
        id: '',
        name: '',
        age: ''
    }
    status.value = "add"
}
// 修改
const editHandle = (index) => {
    formData.value = tableData.value[index]
    status.value = "edit"
}
// 删除
const deleteHandle = (index) => {
    tableData.value.splice(index, 1)
}

onMounted(() => {
    tableData.value = [
        {
            id: '001',
            name: '张三',
            age: '10'
        },
        {
            id: '002',
            name: '李四',
            age: '10'
        },
        {
            id: '003',
            name: '王五',
            age: '10'
        },
    ]
})
</script>

<style scoped></style>